#!/usr/bin/python

#Ganna Raboshchuk {ganna.raboshchuk@upc.edu}
#Updated: 09.01.2015
#UPC, Barcelona

#Comparison of hypothesis and reference block based files.
#--------------------------------------------------------------------------

import os.path
import math
from itertools import izip
import sys

#------------------------------------------------------------------------------
#Global variables.
evaluation_interval = int(sys.argv[1]) #in seconds
gmmOutputFolder = sys.argv[2]
referenceFolder = sys.argv[3] #'/home/anna/Hospital/Segmentation/Alarms_detection/RBMLIB/test/'
C_MS = float(sys.argv[5])
C_FA = float(sys.argv[6])
class_of_interest = sys.argv[7]

CORPUS = ['S3', 'S4', 'S11', 'S12', 'S13', 'S14', 'S15', 'S16', 'S17', 'S18']
SCENARIOS = ['SC1', 'SC2', 'SC3', 'SC4', 'SC5', 'SC6', 'SC7', 'SC8', 'SC9', 'SC10']
EXTRAS = [ '', '_2' ]
TIERS = [ 'alarms' ]

#Indexes of labels
EVENT = 0

total_alarms = [0]*len(CORPUS)
total_others = [0]*len(CORPUS)

total_MS = 0
total_FA = 0
session_MS = [0]*len(CORPUS)
session_FA = [0]*len(CORPUS)
C_det = [0]*len(CORPUS)

i= -1
skip = 0

#------------------------------------------------------------------------------
def getP_target(evaluation_interval):
    total_CORPUS = ['S3', 'S4', 'S11', 'S12', 'S13', 'S14', 'S15', 'S16', 'S17', 'S18']
    total_SCENARIOS = ['SC1', 'SC2', 'SC3', 'SC4', 'SC5', 'SC6', 'SC7', 'SC8', 'SC9', 'SC10']
    alarms = 0
    others = 0
    for session in total_CORPUS:
        for scenario in total_SCENARIOS:
            for extra in EXTRAS:
                for tier in TIERS:
                    path = referenceFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/' + session + '_' + scenario + extra + '.csv'
                    if not os.path.isfile(path):
                        continue
                    else:
                        inputFile = open(path, 'r')
                        with open(path) as fileID:
                            for line in fileID:
                                interval = line.split(',')
                                interval = interval[2]
                                interval = interval.split('\n')
                                if (interval[EVENT] == class_of_interest):
                                    alarms += 1
                                if (interval[EVENT] == 'ot'):
                                    others += 1
    outputFile.write('Overall_Alarm_blocks' + '\t' + str(alarms) + '\t' + 'Overall_Other_blocks' + '\t' + str(others) + '\t' + 'Overall_total_blocks' + '\t' + str(alarms + others) + '\n')
    P_target = float(alarms)/float(alarms + others)
    inputFile.close()
    return P_target

path_results = gmmOutputFolder + '/evaluation_interval_' + str(evaluation_interval) + '/'
outputFile = open(path_results + 'Results.txt', 'w')
for session in CORPUS:
    i += 1
    for scenario in SCENARIOS:
        for extra in EXTRAS:
            for tier in TIERS:
                path_ref = referenceFolder + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/' + session + '_' + scenario + extra + '.csv'
                path_hyp = gmmOutputFolder + '/evaluation_interval_' + str(evaluation_interval) + '/' + session + '/' + session + '_' + scenario + extra + '.csv'
                if not os.path.isfile(path_ref):
                    continue
                else:
                    inputRefFile = open(path_ref, 'r')
                    inputHypFile = open(path_hyp, 'r')
                    with open(path_ref) as fileRefID, open(path_hyp) as fileHypID:
                        for lineRef, lineHyp in izip(fileRefID, fileHypID):
                            interval_ref = lineRef.split(',')
                            interval_ref = interval_ref[2]
                            interval_ref = interval_ref.split('\n')
                            interval_hyp = lineHyp.split(',')
                            interval_hyp = interval_hyp[2]
                            interval_hyp = interval_hyp.split('\n')
                            if (interval_ref[EVENT] == class_of_interest):
                                total_alarms[i] += 1
                            if (interval_ref[EVENT] == 'ot'):
                                total_others[i] += 1
                            if (interval_ref[EVENT] == class_of_interest and interval_hyp[EVENT] == 'ot'):
                                total_MS += 1
                                session_MS[i] += 1
                            if (interval_ref[EVENT] == 'ot' and interval_hyp[EVENT] == class_of_interest):
                                total_FA += 1
                                session_FA[i] += 1
outputFile.write('Total\n')
P_target = getP_target(evaluation_interval)
P_non_target = 1 - P_target
Normalization_factor = C_MS*P_target + C_FA*P_non_target
outputFile.write('Overall_MS' + '\t' + str(total_MS) + '\t' + 'Overall_FA' + '\t' + str(total_FA) + '\n')
outputFile.write('P_target' + '\t' + str(P_target) + '\t' + 'P_non_target' + '\t' + str(P_non_target) + '\n' + '\n')
for x in range(0,len(CORPUS)):
    if (total_alarms[x] == 0 or total_others[x] == 0):
        skip += 1
        outputFile.write(CORPUS[x] + '\n' + 'MS' + '\t' + str(session_MS[x]) + '\t' + 'FA' + '\t' + str(session_FA[x]) + '\t' + 'Alarm_blocks' + '\t' + str(total_alarms[x]) + '\t' + 'Other_blocks' + '\t' + str(total_others[x]) + '\t' + 'Total_session_blocks' + '\t' + str(total_alarms[x] + total_others[x]) + '\n' + '\n')
    else: 
        P_MS_target = float(session_MS[x])/float(total_alarms[x])
        P_FA_non_target = float(session_FA[x])/float(total_others[x])
        C_det[x] = (C_MS*P_MS_target*P_target + C_FA*P_FA_non_target*P_non_target)/Normalization_factor
        outputFile.write(CORPUS[x] + '\n' + 'MS' + '\t' + str(session_MS[x]) + '\t' + 'FA' + '\t' + str(session_FA[x]) + '\t' + 'Alarm_blocks' + '\t' + str(total_alarms[x]) + '\t' + 'Other_blocks' + '\t' + str(total_others[x]) + '\t' + 'Total_session_blocks' + '\t' + str(total_alarms[x] + total_others[x]) + '\n' + 'P_MS_target' + '\t' + str(P_MS_target) + '\t' + 'P_FA_non_target' + '\t' + str(P_FA_non_target) + '\n' + 'C_det' + '\t' + str(C_det[x]) + '\n' + '\n')

average_Cdet = (1-sum(C_det)/(len(CORPUS) - skip))*100
outputFile.write('Average C_det per session' + '\t' + str(average_Cdet))

outputFile.close()
